package drrock.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class NanjiServlet extends HttpServlet {
	String[] msgs = new String[]{"mensagem 1","mensagem 2","asdf","qwer","zxcv"};
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String msg = req.getParameter("msg");
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql:///drrock","root", "masterkey");
			Statement stmt = conn.createStatement();
			ResultSet rs =  stmt.executeQuery("select * from Mensagem where ativa is true");
			if(rs.next()){
				msg = rs.getString("msg");
			}
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// Busca / calcula		
		if ( msg == null ) {
			int nextInt = new Random().nextInt(msgs.length);
			msg = msgs[nextInt];
		}
		
		req.setAttribute("msg", msg);
		// dispacha
		req.getRequestDispatcher("index.jsp").forward(req, resp);
		
		
	}

}
